package com.zhou.base.gateway.sample;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/*
 *   ConcurrentSkipListSet是“线程安全”的集合，而TreeSet是非线程安全的。
 *
 *   下面是“多个线程同时操作并且遍历集合set”的示例
 *   (01) 当set是ConcurrentSkipListSet对象时，程序能正常运行。
 *   (02) 当set是TreeSet对象时，程序会产生ConcurrentModificationException异常。
 *
 * @author skywang
 */
@Slf4j
public class ConcurrentSkipListSetDemo1 {

    // TODO: set是TreeSet对象时，程序偶尔会出错(多运行两边就可以复现)。
    private static Set<String> set = new TreeSet<String>();
    //private static Set<String> set = new ConcurrentSkipListSet<String>();

    public static void main(String[] args) {

        new MyThread("a").start();
        new MyThread("b").start();
    }

    private static void printAll() {
        StringBuilder result = new StringBuilder();
        Iterator iter = set.iterator();
        while (iter.hasNext()) {
            String value = (String) iter.next();
            result.append(value).append(",");
        }
        log.info("{}", result.substring(0, result.length() - 1));
    }

    private static class MyThread extends Thread {
        MyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            int i = 0;
            while (i++ < 10) {
                String val = Thread.currentThread().getName() + (i % 6);
                set.add(val);
                printAll();
            }
        }
    }
}
